package com.hupu.jrs.widget

import android.content.Context
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hupu.jrs.R

/**
 * Created by sll on 2016/4/7.
 */
class LoadMoreRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context, attrs, defStyle) {

    private var mIsFooterEnable = false//是否允许加载更多

    private var mAutoLoadAdapter: AutoLoadAdapter? = null

    private var mIsLoadingMore: Boolean = false
    private var mLoadMorePosition: Int = 0
    private var mListener: LoadMoreListener? = null

    /**
     * 获取最后一条展示的位置
     */
    private val lastVisiblePosition: Int
        get() {
            val position: Int
            if (layoutManager is LinearLayoutManager) {
                position = (layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
            } else if (layoutManager is GridLayoutManager) {
                position = (layoutManager as GridLayoutManager).findLastVisibleItemPosition()
            } else if (layoutManager is StaggeredGridLayoutManager) {
                val layoutManager = layoutManager as StaggeredGridLayoutManager
                val lastPositions = layoutManager.findLastVisibleItemPositions(IntArray(layoutManager.spanCount))
                position = getMaxPosition(lastPositions)
            } else {
                position = layoutManager.itemCount - 1
            }
            return position
        }

    init {
        init()
    }

    private fun init() {
        addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (null != mListener && mIsFooterEnable && !mIsLoadingMore && dy > 0) {
                    val lastVisiblePosition = lastVisiblePosition
                    if (lastVisiblePosition + 1 == mAutoLoadAdapter!!.itemCount) {
                        setLoadingMore(true)
                        mLoadMorePosition = lastVisiblePosition
                        mListener!!.onLoadMore()
                    }
                }
            }
        })
    }

    /**
     * 设置加载更多的监听
     */
    fun setLoadMoreListener(listener: LoadMoreListener) {
        mListener = listener
    }

    /**
     * 设置正在加载更多
     */
    fun setLoadingMore(loadingMore: Boolean) {
        this.mIsLoadingMore = loadingMore
    }

    /**
     * 加载更多监听
     */
    interface LoadMoreListener {
        /**
         * 加载更多
         */
        fun onLoadMore()
    }

    /**
     *
     */
    inner class AutoLoadAdapter(
            /**
             * 数据adapter
             */
            private val mInternalAdapter: RecyclerView.Adapter<*>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        override fun getItemViewType(position: Int): Int {
            val footerPosition = itemCount - 1

            if (footerPosition == position && mIsFooterEnable) {
                return TYPE_FOOTER
            }
            return if (layoutManager is LinearLayoutManager) {
                TYPE_LIST
            } else if (layoutManager is StaggeredGridLayoutManager) {
                TYPE_STAGGER
            } else {
                TYPE_NORMAL
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (viewType == TYPE_FOOTER) {
                FooterViewHolder(LayoutInflater.from(parent.context)
                        .inflate(R.layout.layout_foot_loading, parent, false))
            } else { // type normal
                mInternalAdapter.onCreateViewHolder(parent, viewType)
            }
        }

        inner class FooterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val type = getItemViewType(position)
            if (type != TYPE_FOOTER) {
                mInternalAdapter.onBindViewHolder(holder, position)
            }
        }

        override fun getItemCount(): Int {
            var count = mInternalAdapter.itemCount
            if (mIsFooterEnable) count++

            return count
        }
    }

    override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
        if (adapter != null) {
            mAutoLoadAdapter = AutoLoadAdapter(adapter)
        }
        super.swapAdapter(mAutoLoadAdapter, true)
    }

    /**
     * 获得最大的位置
     */
    private fun getMaxPosition(positions: IntArray): Int {
        val size = positions.size
        var maxPosition = Integer.MIN_VALUE
        for (i in 0 until size) {
            maxPosition = Math.max(maxPosition, positions[i])
        }
        return maxPosition
    }

    /**
     * 设置是否支持自动加载更多
     */
    fun setLoadMoreEnable(autoLoadMore: Boolean) {
        mIsFooterEnable = autoLoadMore
    }

    fun onLoadCompleted(hasMore: Boolean) {
        setLoadMoreEnable(hasMore)
        if (mIsLoadingMore) {
            adapter.notifyItemRemoved(mLoadMorePosition)
        }
        mIsLoadingMore = false
    }

    companion object {
        /**
         * item 类型
         */
        val TYPE_NORMAL = 0
        val TYPE_FOOTER = 1
        val TYPE_LIST = 2
        val TYPE_STAGGER = 3
    }
}
